package com.chenl.provider.题目;

import lombok.SneakyThrows;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Day2 {
    //1.list中的值为MyRun方法的num入参 采用多线程执行MyRun方法,使得num为1的休眠1秒,2的休眠0.5秒,以此类推 最终输出值为 2 1 4 3 这个顺序,并且执行后消耗时间为2秒左右
    @SneakyThrows
    public static void main(String[] args) {//就比如说我构建一份后面需要用的数据,需要调用3个接口,每个接口分别消耗 1 2 3 秒,那是不是我们如果做异步的就可以保证3秒左右,大家同时执行完成,然后获取到他们的结果之后再去规整数据
        List<Integer> list=new ArrayList<>();
        list.add(1);//休眠1秒
        list.add(2);//休眠0.5秒
        list.add(3);//休眠2秒
        list.add(4);//休眠1.5秒
        long start = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(list.size());
        List<Future>futures=new ArrayList<>();
        for (Integer integer : list) {
            switch (integer){
                case 1:
                    Future<?> future = executorService.submit(new MyRun(1000, integer));
                    futures.add(future);
                    break;
                case 2:
                    Future future1 = executorService.submit(new MyRun(500, integer));
                    futures.add(future1);
                    break;
                case 3:
                    Future future2 = executorService.submit(new MyRun(2000, integer));
                    futures.add(future2);
                    break;
                case 4:
                    Future future3 = executorService.submit(new MyRun(1500, integer));
                    futures.add(future3);
                    break;
            }
        }
        executorService.shutdown();
        List<String>resultList=new ArrayList<>();
        for (Future future : futures) {
            resultList.add(String.valueOf(future.get()));
        }
        System.out.println(resultList.toString());
        long end = System.currentTimeMillis();
        System.out.println(BigDecimal.valueOf(end).subtract(BigDecimal.valueOf(start)).divide(BigDecimal.valueOf(1000))+"秒");
    }
    public static class MyRun implements Callable {
        Integer sleepTime;
        Integer number;
        public MyRun(Integer sleepTime,Integer num){//sleepTime:睡眠时间
            this.sleepTime=sleepTime;
            this.number=num;
        }
        @Override
        public Object call() {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(number);
         if (number==1){
             return "11";
         }else if (number==2){
             return "22";
         }else if (number==3){
             return "33";
         }else if (number==4){
             return "44";
         }else {
             return "666";
         }
        }
    }

}
